<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>closure</title>
  <script type="text/javascript">
  <!--
	window.alert=function(s){ console.log(s);};
	function lazy_sum(arr) {
		var sum = function () {
			return arr.reduce(function (x, y) {
				return x + y;
			});
		}
		return sum;
	}
	var f = lazy_sum([1, 2, 3, 4, 5]); // function sum()
	alert(f);
	alert(f()); // 15

	var f1 = lazy_sum([1, 2, 3, 4, 5]);
	var f2 = lazy_sum([1, 2, 3, 4, 5]);
	alert(f1 === f2); // false

	function count() {
		var arr = [];
		for (var i=1; i<=3; i++) {
			arr.push(function () {
				return i * i;
			});
		}
		return arr;
	}
	var results = count();

	var f1 = results[0];
	//var f2 = results[1];
	//var f3 = results[2];
	alert(f1()); // 16
	//alert(f2()); // 16
	//alert(f3()); // 16

	function count() {
		var arr = [];
		for (var i=1; i<=3; i++) {
			arr.push((function (n) {
				return function () {
					return n * n;
				}
			})(i));
		}
		return arr;
	}
	var results = count();

	var f1 = results[0];
	var f2 = results[1];
	var f3 = results[2];
	alert(f1);
	alert(f1()); // 1
	alert(f2()); // 4
	alert(f3()); // 9

	function create_counter(initial) {
		var x = initial || 0;
		return {
			inc: function () {
				x += 1;
				return x;
			}
		}
	}
	var c1 = create_counter();
	alert(c1.inc()); // 1
	alert(c1.inc()); // 2
	alert(c1.inc()); // 3

	var c2 = create_counter(10);
	alert(c2.inc()); // 11
	alert(c2.inc()); // 12
	alert(c2.inc()); // 13

	function make_pow(n) {
		return function (x) {
			return Math.pow(x, n);
		}
	}

	// 创建两个新函数:
	var pow2 = make_pow(2);
	var pow3 = make_pow(3);

	alert(pow2(5)); // 25
	alert(pow3(7)); // 343

  //-->
  </script>
 </head>
 <body>
  
 </body>
</html>
